#include "../include/CharCounter.h"

vector<pair<char, int>> CharCounter::countCharacters(const string& str) {
    vector<pair<char, int>> result;
    unordered_map<char, int> charMap;
    vector<char> order;
    
    for (char c : str) {
        if (charMap.find(c) == charMap.end()) {
            order.push_back(c);
            charMap[c] = 1;
        } else {
            charMap[c]++;
        }
    }
    
    for (char c : order) {
        result.emplace_back(c, charMap[c]);
    }
    
    return result;
}

void CharCounter::printCharacterCount(const vector<pair<char, int>>& count) {
    cout << "字符统计结果:" << endl;
    cout << "字符\t出现次数" << endl;
    cout << "----------------" << endl;
    for (const auto& pair : count) {
        cout << pair.first << "\t" << pair.second << endl;
    }
}

void CharCounter::testCharCounter() {
    cout << "=== 字符统计测试 ===" << endl;
    
    vector<string> testCases = {
        "acbacc",
        "hello world",
        "programming",
        "aabbccddeeff",
        ""
    };
    
    for (const auto& testStr : testCases) {
        cout << "\n输入字符串: \"" << testStr << "\"" << endl;
        if (testStr.empty()) {
            cout << "空字符串" << endl;
            continue;
        }
        auto result = countCharacters(testStr);
        printCharacterCount(result);
    }
}

void CharCounter::interactiveTest() {
    cout << "=== 字符统计交互式测试 ===" << endl;
    
    while (true) {
        cout << "\n请选择操作：" << endl;
        cout << "1. 输入字符串进行统计" << endl;
        cout << "2. 使用默认示例测试" << endl;
        cout << "3. 返回主菜单" << endl;
        
        int choice = Utils::getIntInput("请输入选择 (1-3): ");
        
        if (choice == 3) break;
        
        string inputStr;
        
        if (choice == 1) {
            inputStr = Utils::getStringInput("请输入要统计的字符串: ");
        } else if (choice == 2) {
            inputStr = "acbacc";
            cout << "使用默认示例: \"" << inputStr << "\"" << endl;
        } else {
            cout << "无效选择！" << endl;
            continue;
        }
        
        if (inputStr.empty()) {
            cout << "输入字符串为空！" << endl;
            continue;
        }
        
        auto result = countCharacters(inputStr);
        printCharacterCount(result);
    }
}